package at.jku.ssw.fortress.ui.outline;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.text.Position;

import at.jku.ssw.fortress.ui.ImageConstants;
import at.jku.ssw.fortress.ui.SignatureVisitor;

import com.sun.fortress.nodes.FnAbsDeclOrDecl;
import com.sun.fortress.nodes.Node;
import com.sun.fortress.nodes.ObjectAbsDeclOrDecl;
import com.sun.fortress.nodes.TraitAbsDeclOrDecl;
import com.sun.fortress.nodes.VarAbsDeclOrDecl;

public class Definition {

	private final Node node;
	private List<Definition> children = new ArrayList<Definition>();
	private Definition parent;

	public Definition(Definition parent, Node node) {
		this.parent = parent;
		this.node = node;
	}

	public Position getPosition() {
		int start = node.getSpan().getBegin().getOffset();
		return new Position(start, 0);
	}

	public Definition[] getChildren() {
		return children.toArray(new Definition[children.size()]);
	}
	
	public boolean hasChildren() {
		return !children.isEmpty();
	}
	
	public void addDefiniton(Definition d) {
		children.add(d);
	}
	
	public Definition getParent() {
		return parent;
	}
	
	public String getText() {
		return SignatureVisitor.signature(node);
	}

	public String getImage() {
		if (node instanceof TraitAbsDeclOrDecl) {
			return ImageConstants.ICON_TRAIT;
		}
		if (node instanceof ObjectAbsDeclOrDecl) {
			return ImageConstants.ICON_OBJECT;
		}
		if (node instanceof FnAbsDeclOrDecl) {
			return ImageConstants.ICON_PUBLIC;
		}
		if (node instanceof VarAbsDeclOrDecl) {
			return ImageConstants.ICON_PUBLIC;
		}
		return null;
	}

	public Definition find(int offset) {
		int begin = node.getSpan().getBegin().getOffset();
		int end = node.getSpan().getEnd().getOffset();
		if(begin <= offset && offset < end) {
			for(Definition child : children) {
				Definition res = child.find(offset);
				if(res != null) {
					return res;
				}
			}
			return this;
		}
		return null;
	}

}
